/**
 * 易驰护运 - Login
 * http://menger.me
 * 登录
 * @桓桓
 */
'use strict';
import React from 'react';
import {StyleSheet, Text, TextInput, View, TouchableOpacity, Keyboard} from 'react-native'
import {ListRow, Badge, Checkbox} from '../../components';
import {KeyboardAwareScrollView} from "react-native-keyboard-aware-scroll-view"
import {FormValidation} from '../../utils/validation/FormValidation'
import {inject, observer} from 'mobx-react'

@inject('loginStore')
@observer
export default class Login extends React.Component {
    constructor(props) {
        super(props);
        this.params = this.props.navigation.state.params;
        this.state = {
            checked_one: false,
            time: 60,
            codeBtnText: '获取验证码',
            dataSource: [],
            login_type: 1, // 登录状态：1：密码登录，2：货主、承运商验证码登录，3：司机验证码登录
            emp_no: '', // 手机号
            password: '', // 密码
            code: '',
        }
    }

    componentDidMount () {
        this.requestData()
    }

    requestData = async() => {
        let url = ServicesApi.ARTICLE_ARTICLE_LIST;
        let data = {};
        const result = await Services.post(url, data);
        if (result.code === StatusCode.SUCCESS_CODE) {
            this.setState({
                dataSource: result.data,
            })
        }
    }

    // 获取验证码
    requestGetCodeSms = async () => {
        let {emp_no, time} = this.state
        if (emp_no == '') {
            ToastManager.message('请输入手机号');
            return
        }
        if (time < 60) return false
        let url = ServicesApi.SEND_SMS;
        let data = {
            mobile: emp_no,
            type: 2, // 1：注册时绑定手机号，2：验证码登录时获取验证码，3：忘记密码时验证手机号
            opmode: 1,
            app_type: 2,  // 1货主  2承运商
        };
        let result = await Services.post(url, data);
        if (result.code == StatusCode.SUCCESS_CODE) {
            ToastManager.success('短信发送成功，请注意查收');
            this.countDown()
        } else {
            ToastManager.fail(result.msg);
        }
    };

    // 倒计时
    countDown = () => {
        let {time} = this.state
        this.timer = setInterval(()=> {
            if (time == 0){
                clearInterval(this.timer);
                this.setState({
                    time: 60,
                    codeBtnText: '获取验证码'
                })
            } else{
                this.setState({
                    time: time,
                    codeBtnText: time + '秒后重新获取'
                })
            }
            time--
        }, 1000) 
    }

    // 提交表单
    onSubmit = async () => {
        let {loginStore} = this.props;
        let {checked_one, login_type, emp_no, password, code} = this.state;
        if (checked_one == false) {
            ToastManager.message('请阅读并同意用户服务协议')
            return
        }
        let url = ServicesApi.LOGIN;
        let data = {
            emp_no,
            password,
            code: code,
            type: login_type, // 1：密码登录，2：货主、承运商验证码登录，3：司机验证码登录
            app_type: 2,  // 1货主  2承运商
        };
        let result = await loginStore.doLogin(url, data);
        if (result.code == StatusCode.SUCCESS_CODE) {
            RouterHelper.reset('', 'Tab');
        } else {
            ToastManager.warn(result.msg);
        }
    }

    render() {
        let {checked_one, login_type, emp_no, password, code, codeBtnText, dataSource} = this.state;
        return (
            <PageContainer style={styles.container}>
                <NavigationBar 
                    title={'登录'}
                    style={styles.navigationBar}
                />
                <KeyboardAwareScrollView
                    keyboardShouldPersistTaps={'handled'}
                    style={styles.contentBoxStyle}
                >
                    <ImageView
                        resizeMode={'cover'}
                        style={styles.backGroundImg}
                        source={Images.img_login_bg}
                    />
                    
                        <View style={styles.box}>
                            <View style={styles.logoBox}>
                                <ImageView
                                    resizeMode={'contain'}
                                    style={styles.logo}
                                    source={Images.icon_yc_logo1}
                                />    
                            </View>
                            <View style={styles.header}>
                                <View style={[styles.headerBox, login_type == 1 && styles.headerBoxAchieve]}>
                                    <Text style={[styles.headerText, login_type == 1 && styles.headerTextAchieve]} onPress={() => this.setState({login_type: 1})}>密码登录</Text>
                                </View>
                                <View style={[styles.headerBox, login_type == 2 && styles.headerBoxAchieve]}>
                                    <Text style={[styles.headerText, login_type == 2 && styles.headerTextAchieve]} onPress={() => this.setState({login_type: 2})}>验证码登录</Text>
                                </View>
                            </View>
                            {
                                login_type == 1 
                                ?
                                <View style={styles.form}>
                                    <View style={styles.inputLine}>
                                        <ImageView
                                            resizeMode={'contain'}
                                            style={styles.inputIcon}
                                            source={Images.icon_login_icon1}
                                        />
                                        <TextInput
                                            style={styles.input}
                                            placeholder={'请输入手机号'}
                                            placeholderTextColor={'#999'}
                                            onChangeText={(text) => this.setState({emp_no: text})}
                                            keyboardType={'phone-pad'}
                                            maxLength={11}
                                            defaultValue={emp_no}
                                        />
                                    </View>
                                    <View style={styles.inputLine}>
                                        <ImageView
                                            resizeMode={'contain'}
                                            style={styles.inputIcon}
                                            source={Images.icon_login_icon2}
                                        />
                                        <TextInput
                                            style={styles.input}
                                            placeholder={'请输入密码'}
                                            placeholderTextColor={'#999'}
                                            onChangeText={(text) => this.setState({password: text})}
                                            secureTextEntry={true}
                                            defaultValue={password}
                                        />
                                        {/* <TouchableOpacity style={styles.inputCodeBox} onPress={() => this.requestGetCodeSms()}>
                                            <Text style={styles.inputCode}>{codeBtnText}</Text>
                                        </TouchableOpacity> */}
                                    </View>    
                                </View>
                                :
                                <View style={styles.form}>
                                    <View style={styles.inputLine}>
                                        <ImageView
                                            resizeMode={'contain'}
                                            style={styles.inputIcon}
                                            source={Images.icon_login_icon1}
                                        />
                                        <TextInput
                                            style={styles.input}
                                            placeholder={'请输入用户名'}
                                            placeholderTextColor={'#999'}
                                            onChangeText={(text) => this.setState({emp_no: text})}
                                            keyboardType={'phone-pad'}
                                            maxLength={11}
                                            defaultValue={emp_no}
                                        />
                                    </View>
                                    <View style={styles.inputLine}>
                                        <ImageView
                                            resizeMode={'contain'}
                                            style={styles.inputIcon}
                                            source={Images.icon_login_icon3}
                                        />
                                        <TextInput
                                            style={styles.input}
                                            placeholder={'请输入验证码'}
                                            placeholderTextColor={'#999'}
                                            onChangeText={(text) => this.setState({code: text})}
                                            secureTextEntry={true}
                                            defaultValue={code}
                                        />
                                        <TouchableOpacity style={styles.inputCodeBox} onPress={() => this.requestGetCodeSms()}>
                                            <Text style={styles.inputCode}>{codeBtnText}</Text>
                                        </TouchableOpacity>
                                    </View>    
                                </View>
                            }
                            <View style={styles.loginBtnBox}>
                                <Button
                                    style={styles.loginBtn}
                                    title={'登录'}
                                    titleStyle={styles.loginBtnTitle}
                                    onPress={this.onSubmit}
                                />
                            </View>
                            <View style={styles.bottom}>
                                <Text style={[styles.bottomText, styles.blueText]} numberOfLines={1} onPress={() => RouterHelper.navigate('', 'Register')}>注册新用户</Text>
                                <Text style={styles.bottomText} numberOfLines={1} onPress={() => RouterHelper.navigate('', 'Forget')}>忘记密码?</Text>
                            </View>    
                        </View>

                        <View style={styles.agreement}>
                            <Checkbox
                                style={styles.agreementImg}
                                checked={checked_one}
                                onPress={() => {
                                    if (checked_one === true) {
                                        this.setState({checked_one: false})
                                    } else {
                                        this.setState({checked_one: true})
                                    }
                                }}
                            />
                            <Text style={styles.agreementText}>
                                已阅读并同意
                                <Text 
                                    style={{color: '#0C81FF'}} 
                                    onPress={() => RouterHelper.navigate('', 'Agreement', {
                                        agreementTitle: dataSource[0].title,
                                        agreementUrl: dataSource[0].url
                                    })}
                                >{dataSource[0] && dataSource[0].title}</Text>
                                和
                                <Text 
                                    style={{color: '#0C81FF'}} 
                                    onPress={() => RouterHelper.navigate('', 'Agreement', {
                                        agreementTitle: dataSource[3].title,
                                        agreementUrl: dataSource[3].url
                                    })}
                                >{dataSource[3] && dataSource[3].title}</Text>
                            </Text>
                        </View>
                </KeyboardAwareScrollView>
            </PageContainer>
        );
    }
}
const DominantColor = '#00BFCC';
const SecondaryColor = '#E4E4E4';
const styles = StyleSheet.create({
    // 背景图
    backGroundImg: {
        zIndex: 0,
        position: 'absolute',
        width: SCREEN_WIDTH,
        height: SCREEN_WIDTH * (570 / 1125),
    },
    // 整体居中
    box: {
        alignItems: 'center',
    },
    // 图标
    logoBox: {
        width: 80,
        height: 80,
        borderRadius: 10,
        backgroundColor: '#fff',
        marginTop: SCREEN_WIDTH * (570 / 1125) - 50,
        alignItems: 'center',
        justifyContent: 'center',
        elevation: 20, // 安卓
        shadowOffset: {width: 5, height: 5},
        shadowColor: '#C8C8C8',
        shadowOpacity: 1,
        shadowRadius: 10,
        marginBottom: 20,
    },
    logo: {
        width: 70,
        height: 70,
    },
    // 密码登录/验证码登录
    header: {
        flexDirection: 'row',
        marginBottom: 20,
    },
    headerBox: {
        width: 100,
        height: 30,
        alignItems: 'center',
        justifyContent: 'center',
        borderBottomWidth: 2,
        borderBottomColor: SecondaryColor,
    },
    headerBoxAchieve: {
        borderBottomColor: DominantColor,
    },
    headerText: {
        color: '#BBB',
    },
    headerTextAchieve: {
        color: DominantColor,
    },
    // form
    form: {
        width: SCREEN_WIDTH,
        paddingHorizontal: 30,
        marginBottom: 50,
    },
    inputLine: {
        flexDirection: 'row',
        alignItems: 'center',
        borderBottomWidth: 1,
        borderBottomColor: '#C8C8C8',
    },
    inputIcon: {
        width: 14,
        height: 14,
        marginRight: 8,
    },
    input: {
        flex: 1,
        height: 50,
        paddingHorizontal: 0,
        paddingVertical: 0,
        fontSize: 14,
    },
    inputCodeBox: {
        paddingLeft: 5,
        borderLeftWidth: 1,
        borderLeftColor: DominantColor,
    },
    inputCode: {
        fontSize: 15,
        color: DominantColor,
    },
    // 按钮
    loginBtnBox: {
        marginBottom: 20,
        elevation: 20, // 安卓
        shadowOffset: {width: 1, height: 1},
        shadowColor: DominantColor,
        shadowOpacity: 0.5,
        shadowRadius: 5,
    },
    loginBtn: {
        width: SCREEN_WIDTH - 60,
        height: 36,
        backgroundColor: DominantColor,
        borderRadius: 18,
        paddingHorizontal: 0,
        paddingVertical: 0,
    },
    // bottom
    bottom: {
        width: SCREEN_WIDTH - 60,
        flexDirection: 'row',
        justifyContent: 'space-between',
        alignItems: 'center',
    },
    bottomText: {
        fontSize: 14,
    },
    blueText: {
        color: '#0C81FF',
    },

    agreement: {
        flexDirection: 'row',
        justifyContent: 'center',
        alignItems: 'center',
        paddingBottom: 15,
        paddingTop: 50,
    },
    agreementImg: {
        marginRight: 6,
    },
    agreementText: {
        fontSize: 14,
    },
});
